import { useState, useMemo, useEffect } from 'react';
import _ from 'lodash';
import ShapeCode from './ShapeCode';
import Undo from '../../assets/svg/undo';
import Redo from '../../assets/svg/redo';
import Copy from '../../assets/svg/copy';
import Shear from '../../assets/svg/shear';
import Paste from '../../assets/svg/paste';
import Delete from '../../assets/svg/delete';
import Grid from '../../assets/svg/grid';
import Narrow from '../../assets/svg/narrow';
import Enlarge from '../../assets/svg/enlarge';
import Keyboard from '../../assets/svg/keyboard';
import { viewKeyboard } from '../operations';
import { canOperate1, canOperate2 } from '../utils';
import './style.less';

export default function ToolBar(props: any) {
  const {
    customModeler,
    curElement,
    setVariableDrawerVisiable,
    setVersionVisiable,
    setPropertiesPanelVisiable,
    customPropertiesPanelRef,
    customPaletteRef,
  } = props;
  const [percent, setPercent] = useState(1);

  const handlerZoom = (radio: any) => {
    const newScale = !radio ? 1.0 : percent + radio;
    customModeler.get('canvas').zoom(newScale);
    setPercent(newScale);
  };

  const canUndo = useMemo(() => {
    if (customModeler) {
      return customModeler?.get('commandStack')?.canUndo();
    }
  }, [customModeler?.get('commandStack')._stackIdx]);

  const canRedo = useMemo(() => {
    if (customModeler) {
      return customModeler?.get('commandStack')?.canRedo();
    }
  }, [customModeler?.get('commandStack')._stackIdx]);

  const openGlobalSetting = () => {
    if (!customModeler) {
      return;
    };
    setPropertiesPanelVisiable(true);
    setVariableDrawerVisiable(false);
    setVersionVisiable(false);
    customPropertiesPanelRef?.current?.setCurElement(null);
    let _selectedElements = customModeler.get('selection')._selectedElements;
    _selectedElements.forEach((item: any) => {
      customModeler.get('selection').deselect(item);
    });
  };

  const options = useMemo(() => {
    return [
      {
        key: 'undo',
        title: '撤销',
        img: Undo,
        onClick: () => {
          if (!canUndo) {
            return;
          }
          customModeler.get('commandStack').undo();
        },
      },
      {
        key: 'redo',
        title: '恢复',
        img: Redo,
        onClick: () => {
          if (!canRedo) {
            return;
          }
          customModeler.get('commandStack').redo();
        },
      },
      {
        key: 'copy',
        title: '复制',
        img: Copy,
        onClick: () => {
          if (curElement && curElement?.length) {
            let canCopyElement = curElement?.filter(canOperate1);
            if (!_.isEmpty(canCopyElement)) {
              customModeler.get('copyPaste').copy(canCopyElement);
            }
          }
        },
      },
      {
        key: 'shear',
        title: '剪切',
        img: Shear,
        onClick: () => {
          if (curElement && curElement?.length) {
            let canShearElement = curElement?.filter(canOperate2);
            if (!_.isEmpty(canShearElement)) {
              setPropertiesPanelVisiable(false);
              const shearIds = canShearElement?.map((item: { id: string; }) => item?.id);
              customModeler.get('customRenderer').shearCache = shearIds;
              customModeler.get('copyPaste').copy(canShearElement);
              customModeler.get('modeling').removeElements(canShearElement);
              customModeler.get('copyPaste').paste(canShearElement);
            }
          }
        },
      },
      {
        key: 'paste',
        title: '粘贴',
        img: Paste,
        onClick: () => {
          if (curElement && curElement?.length) {
            let canPasteElement = curElement?.filter(canOperate1);
            if (!_.isEmpty(canPasteElement)) {
              // 框选多个元素的粘贴会报错，暂时没找到原因
              customModeler.get('copyPaste').paste(canPasteElement);
            }
          }
        },
      },
      {
        key: 'delete',
        title: '删除',
        img: Delete,
        onClick: () => {
          if (curElement && curElement?.length) {
            let canDeleteElement = curElement?.filter(canOperate2);
            if (!_.isEmpty(canDeleteElement)) {
              // setPropertiesPanelVisiable(false);
              customModeler.get('modeling').removeElements(canDeleteElement);
            }
          }
        },
      },
      {
        key: 'grid',
        title: '网格',
        img: Grid,
        onClick: () => {
          let _container = document.getElementById('bpmnCanvas');
          if (_container) {
            if (_container?.classList.value.includes('noGrid')) {
              _container.classList.remove('noGrid');
            } else {
              _container.classList.add('noGrid');
            }
          }
        },
      },
      {
        key: 'keyboard',
        title: '快捷键',
        img: Keyboard,
        onClick: () => {
          viewKeyboard({ customPaletteRef });
        },
      },
      {
        key: 'narrow',
        title: '缩小',
        img: Narrow,
        onClick: () => {
          if (percent < 0.7) {
            return;
          }
          handlerZoom(-0.1);
        },
      },
      {
        key: 'proportion',
        title: '比例',
        text: Math.round(percent * 100) + '%',
        onClick: () => {
          handlerZoom(0);
        },
      },
      {
        key: 'enlarge',
        title: '放大',
        img: Enlarge,
        onClick: () => {
          if (percent > 2) {
            return;
          }
          handlerZoom(0.1);
        },
      },
    ];
  }, [customModeler, handlerZoom, percent, canUndo, canRedo, curElement, canOperate1, canOperate2, customPropertiesPanelRef]);

  useEffect(() => {
    if (customModeler) {
      const Canvas = customModeler.get('canvas');
      // @ts-ignore
      document.getElementById('bpmnCanvas').addEventListener('wheel', (event) => {
        event.preventDefault();
        let _percent = percent;
        if (percent < 0.7 || percent > 2) {
          return;
        };
        const delta = event.deltaY;
        if (delta > 0) {
          _percent -= 0.1
        } else {
          _percent += 0.1;
        };
        Canvas.zoom(_percent);
        setPercent(_percent);
      });
    }
  }, [customModeler, document.getElementById('bpmnCanvas'), percent])

  return (
    <div className='bpmn-tool-bar'>
      <div className='bpmn-tool-bar-options'>
        {options?.map((item: any) => {
          return (
            <div
              key={item.key}
              className='bpmn-tool-bar-options-item'
              onClick={() => {
                if (!customModeler) {
                  return;
                };
                item?.onClick();
              }}
            >
              {item?.img ? (
                <div
                  className={`bpmn-tool-bar-options-item-img`}
                  title={item?.title}
                >
                  <item.img />
                </div>
              ) : (
                <div className='bpmn-tool-bar-options-item-text'>{item?.text}</div>
              )}
            </div>
          );
        })}
        <div
          className='bpmn-tool-bar-global-btn'
          onClick={openGlobalSetting}
        >
          全局设置
        </div>
      </div>
      {/* <div className='bpmn-tool-bar-btn'>
        <div>
          <ShapeCode
            text='图形定义'
            onClick={() => {
              setCurrent('shape');
            }}
            cur={current == 'shape'}
          />
          <ShapeCode
            text='查看源码'
            onClick={() => {
              setPropertiesPanelVisiable(false);
              setCurrent('code');
            }}
            cur={current == 'code'}
          />
        </div>
      </div> */}
    </div>
  );
}
